package com.zmj.base.file.controller;

import com.zmj.base.file.service.FileService;
import com.zmj.framework.response.Result;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = {"文件管理"})
@Slf4j
@RestController
@RequestMapping("/v1/file")
public class FileController {

    @Autowired
    FileService fileService;

    @ApiOperation(value = "文件上传", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentPath", value = "路径(空则根目录，枚举表：holli-form：表单)", required = false, dataType = "string", paramType = "query")})
    @PostMapping(value = "/upload")
    public Result fileUpload(@RequestParam(value = "parentPath",required = false) String parentPath,
                                 @ApiParam(value = "上传文件") @RequestParam(value = "file") MultipartFile file) {
        String uri;
        try {
            uri = fileService.saveItem(parentPath,file);
            return Result.success(uri);
        }catch (RuntimeException e){
            log.error("文件上传失败",e);
            return Result.fail("文件上传失败");
        }
    }

    /**
     * 删除文件
     * @param fileUrl
     * @return
     */
    @ApiOperation(value = "删除文件", notes = "删除文件")
    @DeleteMapping(value = "/deleteFile")
    public Result deleteFile(@RequestParam(value = "fileUrl", required = false) String fileUrl) {
        try {
            fileService.deleteFile(fileUrl);
            return Result.success("文件删除成功");
        }catch (RuntimeException e){
            return Result.fail("文件删除失败");
        }
    }
}
